<script setup lang="ts">
import Detail from './page/Detail.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { PropType, h, reactive, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter, useRoute } from 'vue-router'
import { getApi } from '@/api/lowcode'
import { ElTag, ElInput, ElButton } from 'element-plus'
import { PageDataProperty } from '../../../types/Lowcode'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'

const props = defineProps({
  pageConfig: {
    type: Object as PropType<PageDataProperty>,
    required: true
  }
})

const { push, go } = useRouter()

const { params } = useRoute()

const { t } = useI18n()

const currentRow = ref<Nullable<any>>(null)

const getTableDet = async () => {
  const res = await getApi(props.pageConfig.detailApi, params.rid as string)
  if (res) {
    currentRow.value = res.data
  }
}

const crudSchemas = reactive<CrudSchema[]>(props.pageConfig.schemas)
crudSchemas.forEach((column: CrudSchema) => {
  if (column.detail?.slots) {
    for (let slotName in column.detail?.slots) {
      let funcStr = column.detail?.slots[slotName]
      if (!funcStr) {
        delete column.detail.slots[slotName]
        continue
      }
      column.detail.slots[slotName] = (data) => {
        try {
          return customFunction(data, funcStr)
        } catch (e: any) {
          console.error(e.message)
          return data.row[column.field]
        }
      }
    }
  }
})

const customFunction = (data: any, funcStr: string) => {
  const Fn = new Function('VUECustom', funcStr)
  let VUECustom = { h, ElTag, ElInput, data: data }
  return Fn(VUECustom)
}

getTableDet()
</script>

<template>
  <ContentDetailWrap :title="t('exampleDemo.detail')" @back="push('/example/example-page')">
    <template #header>
      <ElButton @click="go(-1)">
        {{ t('common.back') }}
      </ElButton>
    </template>
    <Detail :page-config="pageConfig" :current-row="currentRow" />
  </ContentDetailWrap>
</template>
